import { defineStore } from "pinia";
import { ref, computed } from "vue";

interface SystemMessage {
  id: number;
  type: 'system' | 'payment' | 'medical' | 'appointment';
  title: string;
  content: string;
  createTime: string;
  isRead: boolean;
  actionUrl?: string;
  actionText?: string;
}

interface AppointmentInfo {
  id: number;
  orderNo: string;
  department: string;
  doctorName: string;
  date: string;
  time: string;
  fee: number;
  status: '待就诊' | '已完成' | '已取消';
}

interface MedicalRecord {
  id: number;
  date: string;
  department: string;
  doctorName: string;
  diagnosis: string;
  prescription?: string;
}

export const useMessageStore = defineStore("message", () => {
  // 系统消息
  const messages = ref<SystemMessage[]>([]);
  
  // 未读消息数量
  const unreadCount = computed(() => {
    return messages.value.filter(msg => !msg.isRead).length;
  });

  // 添加消息
  const addMessage = (message: Omit<SystemMessage, 'id'>) => {
    const newMessage: SystemMessage = {
      ...message,
      id: Date.now() + Math.random()
    };
    messages.value.unshift(newMessage);
  };

  // 标记消息为已读
  const markAsRead = (messageId: number) => {
    const message = messages.value.find(msg => msg.id === messageId);
    if (message) {
      message.isRead = true;
    }
  };

  // 删除消息
  const deleteMessage = (messageId: number) => {
    const index = messages.value.findIndex(msg => msg.id === messageId);
    if (index > -1) {
      messages.value.splice(index, 1);
    }
  };

  // 全部标记为已读
  const markAllAsRead = () => {
    messages.value.forEach(msg => {
      msg.isRead = true;
    });
  };

  // 清空消息
  const clearMessages = (type?: string) => {
    if (type && type !== 'all') {
      messages.value = messages.value.filter(msg => msg.type !== type);
    } else {
      messages.value = [];
    }
  };

  // 创建预约相关消息
  const createAppointmentMessage = (appointment: AppointmentInfo, type: 'created' | 'reminder' | 'completed' | 'cancelled') => {
    let title = '';
    let content = '';
    let messageType: SystemMessage['type'] = 'appointment';

    switch (type) {
      case 'created':
        title = '预约成功';
        content = `您已成功预约${appointment.doctorName}医生，就诊时间：${appointment.date} ${appointment.time}，请按时就诊。`;
        messageType = 'appointment';
        break;
      case 'reminder':
        title = '就诊提醒';
        content = `您预约的${appointment.doctorName}医生门诊将于明天开始，请提前30分钟到达医院。`;
        messageType = 'appointment';
        break;
      case 'completed':
        title = '就诊完成';
        content = `您的就诊已完成，诊疗记录已更新，可在个人中心查看。`;
        messageType = 'medical';
        break;
      case 'cancelled':
        title = '预约取消';
        content = `您的预约已取消，挂号费将原路退回。`;
        messageType = 'payment';
        break;
    }

    addMessage({
      type: messageType,
      title,
      content,
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      isRead: false,
      actionUrl: '/pages/profile/appointment-history',
      actionText: '查看详情'
    });
  };

  // 创建支付相关消息
  const createPaymentMessage = (amount: number, type: 'success' | 'failed') => {
    addMessage({
      type: 'payment',
      title: type === 'success' ? '缴费成功' : '缴费失败',
      content: type === 'success' 
        ? `您的费用￥${amount}已成功支付，请保留好缴费凭证。`
        : `您的费用￥${amount}支付失败，请重新尝试支付。`,
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      isRead: false,
      actionUrl: '/pages/profile/appointment-history'
    });
  };

  // 创建医嘱消息
  const createMedicalAdviceMessage = (advice: string) => {
    addMessage({
      type: 'medical',
      title: '医嘱提醒',
      content: advice,
      createTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      isRead: false
    });
  };

  return {
    messages,
    unreadCount,
    addMessage,
    markAsRead,
    deleteMessage,
    markAllAsRead,
    clearMessages,
    createAppointmentMessage,
    createPaymentMessage,
    createMedicalAdviceMessage
  };
}, {
  persist: true
});
